<?php
namespace Hilaoyu\Utils;

/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/3/8
 * Time: 9:45
 *
 * 远程http交互类
 *
 *
 */


class UtilHtml {
    static public function formatHtmlOptions($arr,$value_key='value',$label_key='label',$name='',$checked=[],$checked_key=''){
        $value_key = trim($value_key);
        $label_key = trim($label_key);
        $checked_key = trim($checked_key);
        $options = [];
        foreach ((array)$arr as $item){
            $item = (array)$item;
            $replaces = [];
            foreach ($item as $ik => $iv){
                $iv = $iv;
                $item[$ik] = $iv;

                $replace_key = ':' . $ik . ':';
                $replaces[$replace_key] = $iv;
            }


            $option_name = UtilStr::replace($name,$replaces);

            $option_value = $item[$value_key] ?? '';
            $option_label = $item[$label_key] ?? '';

            $checked_value = $checked_key ? ($item[$checked_key] ?? '') : $option_value;

            $option_checked = is_array($checked)
                ? (in_array($checked_value,$checked))
                : ($checked_value == $checked);

            $options[] = [
                'name'=>$option_name,
                'value'=>$option_value,
                'label'=>$option_label,
                'checked'=>$option_checked,
            ];
        }

        return $options;
    }

    static public function statusOptions($selected=[],string $add_title='',$true_title='',$false_title=''){
        $options = [
            ['value'=>1,'label'=>('' != $true_title) ? $true_title : '是'],
            ['value'=>0,'label'=>('' != $false_title) ? $false_title :'否'],
        ];

        if($add_title){
            array_unshift($options,['value'=>'','label'=>trim($add_title)]);
        }

        return static::formatHtmlOptions($options,'value','label','',$selected);
    }


    static public function sexOptions($selected=[],$add_title=false){
        $options = [
            ['value'=>'男','label'=>'男'],
            ['value'=>'女','label'=>'女'],
            ['value'=>'保密','label'=>'保密'],
        ];

        if($add_title){
            array_unshift($options,['value'=>'','label'=>'性别']);
        }

        return static::formatHtmlOptions($options,'value','label','',$selected);
    }
}
